package isr.cloudgate.dashboard.servlet;

import isr.cloudgate.dashboard.properties.Messages;
import isr.google.gdata.GDataClient;
import isr.google.gdata.data.GoogleUser;

import java.io.IOException;
import java.util.Locale;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {

	private static final Logger logger = Logger.getLogger(LoginServlet.class
		.getName());
	private static final long serialVersionUID = 1L;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest
	 * , javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		logger.info("login request (post)");

		Locale locale = ServletUtilities.checkLanguage(request);

		String adminUser = request.getParameter("admin_user");
		String adminPassword = request.getParameter("admin_password");
		String domain =
			adminUser.contains("@") ? adminUser.split("@")[1] : null;

		logger.info("login user: " + adminUser);

		String message;
		if (domain == null)
			message = Messages.getString(locale, Messages.Key.NO_DOMAIN);

		else {

			GDataClient appsClient = null;

			try {

				/* check login */
				appsClient = new GDataClient(adminUser, adminPassword, domain);
				GoogleUser tmpUser = appsClient.getUser(adminUser);

				if (tmpUser == null) {

					message =
						Messages.getString(locale, Messages.Key.LOGIN_FAILURE);

				} else {

					ServletUtilities.setAdminData(request, adminUser,
						adminPassword);

					message =
						Messages.getString(locale, Messages.Key.LOGIN_SUCCESS);
					request.setAttribute("admin", adminUser);

				}

			} catch (Exception e) {

				logger.info("login failed: " + e);
				message =
					Messages.getString(locale, Messages.Key.LOGIN_FAILURE)
						+ ": " + e.toString();

			}
		}

		logger.info("request message: " + message);

		request.setAttribute("userMessage", message);
		request.setAttribute("admin_user", adminUser);

		String nextPage = JspPage.main;
		request.getRequestDispatcher(nextPage).forward(request, response);

	}

}
